local hx__junju = fk.CreateSkill {
  name = "hx__junju",
  tags = { Skill.Compulsory, },
}

local U = require "packages/utility/utility"

hx__junju:addEffect(fk.GameStart, {
  anim_type = "control",
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(hx__junju.name) then return false end
    local cards2 = player:getCardIds(Player.Hand)
    if #cards2 > 0 then
      event:setCostData(self, cards2)
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local cards = event:getCostData(self)
    if event == fk.GameStart then
      local ids = room:getCardsFromPileByRule(".|.|.", 2, "drawPile")
      if #ids > 0 then
        room:moveCards({
          ids = ids,
          to = player,
          toArea = Card.PlayerHand,
          moveReason = fk.ReasonJustMove,
          proposer = player,
          skillName = hx__junju.name,
        })
      end
    end
  end,
})

hx__junju:addEffect(fk.AfterCardsMove, {
  anim_type = "control",
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(hx__junju.name) or #player:getCardIds("h") == 0 then return false end
    local cards = {}
    if event == fk.AfterCardsMove then
      table.insertIfNeed(cards, player:getCardIds("h"))
      cards = player.room.logic:moveCardsHoldingAreaCheck(cards)
      if #cards > 0 then
        event:setCostData(self, cards)
        return true
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local cards = event:getCostData(self)
    player:addToPile("$hx__junju&", cards, false, hx__junju.name, player, nil)
  end,
})


hx__junju:addEffect(fk.BeforeDrawCard, {
  anim_type = "negative",
  on_use = function(self, event, target, player, data)
    local room = player.room
    local num = data.num
    local discard = #room.discard_pile
    if discard >= num then
      data.num = 0
      local ids = room:getCardsFromPileByRule(".|.|.", num, "discardPile")
      if #ids > 0 then
        room:moveCards({
          ids = ids,
          to = player,
          toArea = Card.PlayerHand,
          moveReason = fk.ReasonJustMove,
          proposer = player,
          skillName = hx__junju.name,
        })
      end
    else
      data.num = 0
      local ids = room:getCardsFromPileByRule(".|.|.", discard, "discardPile")
      if #ids > 0 then
        room:moveCards({
          ids = ids,
          to = player,
          toArea = Card.PlayerHand,
          moveReason = fk.ReasonJustMove,
          proposer = player,
          skillName = hx__junju.name,
        })
      end
    end
  end,
})

return hx__junju